<?php
namespace App\Admin\Controllers\Purchase;

use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\SysIArea;
use App\Models\Product\ProductClassify;
use App\Models\Stocking\StockingApplyDetail;
use App\Util\RExcel;
use App\Util\User;
use App\Admin\Actions\Purchase\PlanBatchClose;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Support\Facades\Request;

class PlanDetailController extends AdminController{

    protected $title = '采购计划关闭';

    protected function grid()
    {
        $grid = new Grid(new StockingApplyDetail());
        $grid->model()->orderBy('status', 'ASC');
        $grid->model()->orderBy('id', 'DESC');
        $grid->column('stocking_no','备货单号')->link(function ($model){
            return "/xqc/stocking/search?stocking_no=$model->stocking_no";
        });
        $grid->column('area.area','站点');
        $grid->column('apply.seller_id','备货员')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('sku.psku_code','SKU');
        $grid->column('sku.psku_cn','产品名称')->style('max-width:150px');
        $grid->column('skuClassify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('skuClassify.title','品类')->style('max-width:120px');
        $grid->column('apply_detail_num','备货数量');
        $grid->column('plan_num','已计划数量');
        $grid->column('status','单据状态')->display(function ($value){
            return StockingApplyDetail::$_status[$value];
        });
        $grid->column('plan_status','计划状态')->display(function ($value){
            return StockingApplyDetail::$_planStatus[$value];
        })->filter(StockingApplyDetail::$_planStatus);
        $grid->column('pur_status','采购状态')->display(function ($value){
            return StockingApplyDetail::$_purStatus[$value];
        })->filter(StockingApplyDetail::$_purStatus);
        $grid->column('re_status','收获状态')->display(function ($value){
            return StockingApplyDetail::$_reStatus[$value];
        })->filter(StockingApplyDetail::$_reStatus);
        $grid->disableActions();
        $grid->batchActions(function ($batch) {
            $batch->disableDelete();
            $batch->add(new PlanBatchClose()); //关闭采购单
        });
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('purchase/plan-detail-download'));
        });
        $grid->disableCreateButton();
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('stocking_no','备货单');
                $filter->equal('area_id','站点')->select(SysIArea::options());
            });
            $filter->column(1/3, function ($filter){
                $filter->equal('apply.seller_id', '备货员')->select(User::getUserOptions());
                $filter->equal('skuClassify.season', '季节性')->select(ProductClassify::$_season);
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('status', '状态')->select(StockingApplyDetail::$_status);
            });
        });

        return $grid;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        //备货单明细
        $query = StockingApplyDetail::query()
            ->orderBy('status', 'ASC')
            ->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'skuClassify'){
                $query->whereHas('skuClassify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if(in_array($key,['status','seller_id','stocking_no','area_id'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['备货单号','站点','备货员','SKU','产品名称','季节性','品类','备货数量','已计划数量',
            '单据状态','计划状态','采购状态','收货状态','创建日期'];
        RExcel::exportCsv('采购计划明细',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::_getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    private static function _getDownloadData($res)
    {
        $seller = [];
        foreach ($res as $model){
            $sellerId = $model->apply->seller_id ?: 0;
            if(!array_key_exists($sellerId,$seller)){
                $seller[$sellerId] = User::getUsernameById($sellerId);
            }
            $temp = [
                $model->stocking_no,
                $model->area->area ?? '',
                $seller[$sellerId],
                $model->sku->psku_code ?? '',
                $model->sku->psku_cn ?? '',
                ProductClassify::$_season[$model->skuClassify->season ?? 3],
                $model->skuClassify->title ?? '',
                $model->apply_detail_num ?: 0,
                $model->plan_num ?: 0,
                StockingApplyDetail::$_status[$model->status],
                StockingApplyDetail::$_planStatus[$model->plan_status],
                StockingApplyDetail::$_purStatus[$model->pur_status],
                StockingApplyDetail::$_reStatus[$model->re_status],
                $model->created_at,
            ];
            yield $temp;
        }
    }
}
